-- Block 2
-- completion setup
local cmp = require('cmp')

local home = os.getenv('HOME')

cmp.setup({
	snippet = {
		expand = function(args)
			vim.fn["vsnip#anonymous"](args.body)
		end,
	},
	window = {
		completion = cmp.config.window.bordered(),
		documentation = cmp.config.window.bordered(),
	},
	mapping = cmp.mapping.preset.insert({
		['<C-b>'] = cmp.mapping.scroll_docs(-4),
		['<C-f>'] = cmp.mapping.scroll_docs(4),
		['<C-Space>'] = cmp.mapping.complete(),
		['<C-e>'] = cmp.mapping.abort(),
		['<CR>'] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
	}),
	sources = cmp.config.sources({
			{ name = 'nvim_lsp' },
			{ name = 'vsnip' }
		},
		{
			{ name = 'buffer' }
		})
})

cmp.setup.cmdline(':', {
	mapping = cmp.mapping.preset.cmdline(),
	sources = cmp.config.sources({
		{ name = 'path' }
	}, {
		{ name = 'cmdline' }
	})
})

local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities)

-- end of Block 2

-- Block 1
-- These lines go first in order to start lsp
-- this lsp has to be built from source, and cmd path varies from
-- where you put the actual binary
vim.lsp.start({
	name = "lua-server",

	cmd = { home .. "/install/lua-language-server/bin/lua-language-server" },
	root_dir = vim.fs.dirname(vim.fs.find({ '.root', 'init.lua' }, { upward = true })[1]),
	-- passing capabilities created by cmp to language server
	capabilities = capabilities
})
-- end of Block 1

vim.api.nvim_create_autocmd('LspAttach', {
	callback = function(args)
		local client = vim.lsp.get_client_by_id(args.data.client_id)
		if client.server_capabilities.hoverProvider then
			vim.keymap.set('n', '<space>f', vim.lsp.buf.format)
		end
	end
})
